<template>
  <div class="video-js-container">
    <video v-show="!loadError" :id="id" class="video-js vjs-default-skin" preload="auto"></video>
    <div v-show="loadError" class="error">加载失败</div>
  </div>
</template>

<script setup>
import videojs from 'video.js/dist/video.min.js'
import 'video.js/dist/video-js.min.css'
import { onUnmounted, onMounted, watch, ref } from 'vue'

const props = defineProps({
  id: {
    type: String,
    default: '',
  },
  url: {
    type: String,
    default: '',
  },
})
let player = null
let src = props.url
const options = {
  sources: {
    src,
    type: 'application/x-mpegURL',
  },
  muted: true,
  autoplay: true,
  bigPlayButton: false, //是否显示大播放按钮
  textTrackDisplay: false, //是否显示字幕轨道
  posterImage: false, //是否显示海报图像
  errorDisplay: false, //是否显示错误信息
  controls: false, //是否显示控制条
  controlBar: {
    playToggle: true, // 播放/暂停按钮
    progressControl: true, // 进度条
    volumePanel: true, // 音量控制
    fullscreenToggle: true, // 全屏按钮
    currentTimeDisplay: true, // 当前时间显示
    durationDisplay: true, // 总时长显示
    remainingTimeDisplay: true, // 剩余时间显示
  }, //控制条的配置
}
const loadError = ref(false)
// 开始请求
const handleLoadStart = () => {
  loadError.value = false
}
// 请求失败
const handleError = () => {
  loadError.value = true
}

const initVideo = () => {
  player = videojs(`${props.id}`, options, function () {
    player.on('loadstart', handleLoadStart)
    player.on('error', handleError)
  })
}
watch(
  () => props.url,
  (newUrl) => {
    if (player) {
      player.src({
        src: newUrl,
        type: 'application/x-mpegURL',
      })
    }
  },
)
onMounted(() => {
  initVideo()
})
onUnmounted(() => {
  player?.dispose()
})
</script>

<style lang="scss" scoped>
.video-js-container,
.video-js {
  width: 100% !important;
  height: 100% !important;
}
.video-js-container {
  position: relative;
  .error {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 28px;
    color: #fff;
  }
}
</style>
